package setup

import (
	"github.com/99designs/gqlgen/graphql/playground"
	ginzap "github.com/gin-contrib/zap"
	"github.com/gin-gonic/gin"
	"github.com/shinedone/srv-framework/pkg/asserts"
	"github.com/shinedone/srv-server/internal/global/instance"
	enterpriseGqlgen "github.com/shinedone/srv-server/internal/modules/enterprise/gqlgen"
	"go.uber.org/zap"
	"net"
	"time"
)

// 初始化Gqlgen
func GqlgenInit(errCh chan error) {
	config := instance.GetConfig()
	appLog := instance.GetAppLog()
	kitLog := instance.GetKitLog()
	httpAddress := config.Gql.Address
	httpListener, err := net.Listen("tcp", httpAddress)
	asserts.Nil(err, err)
	// gin设置
	gin.SetMode(gin.ReleaseMode)
	ginLogger := appLog.WithOptions(zap.WithCaller(false))
	router := gin.Default()
	// 设置通用中间件
	router.Use(ginzap.Ginzap(ginLogger, time.RFC3339, true))
	router.Use(ginzap.RecoveryWithZap(ginLogger, true))
	// 注册路由
	gqlRouterRegister(router)
	// http启动
	go func() {
		_ = kitLog.Log("transport", "HTTP", "addr", httpAddress)
		errCh <- router.RunListener(httpListener)
	}()
}

// 路由注册
func gqlRouterRegister(router *gin.Engine) {
	// 初始化gqlgen handler

	router.GET("play", playgroundHandler())

	enterpriseGqlHandler := enterpriseGqlgen.NewGqlHandler()
	router.Any("adm/enterprise/gql/query", enterpriseGqlHandler)
	router.Any("adm/enterprise/gql/mutation", enterpriseGqlHandler)

}

func playgroundHandler() gin.HandlerFunc {
	h := playground.Handler("GraphQL", "/query")

	return func(c *gin.Context) {
		h.ServeHTTP(c.Writer, c.Request)
	}
}
